<?php

class ApiController extends Controller
{
	protected $result = array();

	public function actionIndex()
	{
		echo "Pla2 API , can i help you ?";
		Helper::redir("/", 2);
	}

	public function actionregisterWithUsername(){
		/*
		 * Check Get variable.
		*/
		if ( isset($_GET['username']) and isset($_GET['password']) and isset($_GET['email'])) {
			/*
			 * Set variable
			*/
			$username = $_GET['username'];
			$password = $_GET['password'];
			$email = $_GET['email'];
			/*
			 * Validate Username & Password
			*/
			if ( !Helper::validateEnNumber($username) ) {
				$this->result['errCode'] = 3;
				$this->result['errMsg'] = "Error username En & Number Only";
			} else if ( strlen($username) < 4 ) {
				$this->result['errCode'] = 4;
				$this->result['errMsg'] = "Username Need more than 4 or more.";
			} else if ( Helper::checkPassword($password,8) != null) {
				$result = Helper::checkPassword($password,8);
				$this->result['errCode'] = $result['errCode'];
				$this->result['errMsg'] = $result['errMsg'];
			} else {
				/*
				 * Check Username and Email in database
				*/
				if ( Account::model()->count("username = '" . $username . "' ") > 0 ) {
					$this->result['errCode'] = 56;
					$this->result['errMsg'] = "This username is already in use.";
				} else if ( Account::model()->count("email = '" . $email . "' ") > 0 ) {
					$this->result['errCode'] = 1;
					$this->result['errMsg'] = "This email is already in use.";
				} else {
					/*
					 * Insert new account
					* $acc_token = generator token function from Helper
					* $time_exp = Date time token Expire
					*/
					$acc_token = Helper::genToken();
					$account = new Account;
					$account_token = new AccountToken;
					$time_exp = Helper::DateTimeAdd(1);
					$account->email = $email;
					$account->username = $username;
					$account->password = Helper::hasPass($password);
					if ($account->save()) {
						$account_token->uid = $account->uid;
						$account_token->token = $acc_token;
						$account_token->expireTimeText = $time_exp['text'];
						$account_token->expireTime = $time_exp['date'];
						if ( $account_token->save() ) {
							$this->result['errCode'] = 0x0;
							$this->result['errMsg'] = "";
							$this->result['username'] = $username;
							$this->result['email'] = $email;
							$this->result['token'] = $acc_token;
							$this->result['time_exp'] = $time_exp;
						} else {
							/*
							 * is Error Insert Account Token
							*/
							$this->result['errCode'] = 9;
							$this->result['errMsg'] = "Insert account token error ";
						}
					} else {
						/*
						 * is Error Insert Account
						*/
						$this->result['errCode'] = 8;
						$this->result['errMsg'] = "Insert new account error ";
					}
				}
			}
		} else {
			/*
			 * Error Undefined variable
			*/
			$this->result['errCode'] = 2;
			$this->result['errMsg'] = "Register With Username Undefined variable.";
		}
		echo CJSON::encode($this->result);
	}

	/*
	 * Function API LoginWithUsername
	*/

	public function actionloginWithUsername() {
		/*
		 * Check Variable From Get.
		*/
		if ( isset($_GET['username']) ) {
			$login = $_GET['username'];
		} else {
			$login = null;
		}
		if ( isset($_GET['password'])) {
			$password = $_GET['password'];
		} else {
			$password = null;
		}
		/*
		 * Check Username and password = null
		*/
		if ( $login == null || $password == null ) {
			$this->result['errCode'] = 10;
			$this->result['errMsg'] = "Login With Username Undefined variable.";
		} else {
			/*
			 * Set variable
			*/
			$login = $_GET['username'];
			$password = Helper::hasPass($_GET['password']);
			if ( Account::model()->count("( username = '" . $login . "' OR email = '" . $login . "' ) and password = '" . $password . "'") > 0 ) {
				$account = Account::model()->findAll("( username = '" . $login . "' OR email = '" . $login . "' ) and password = '" . $password . "'");
				$acc_token = Helper::genToken();
				$time_exp = Helper::DateTimeAdd(1);
				if ( AccountToken::model()->updateAll(array("token"=>$acc_token, "expireTimeText"=>$time_exp['text'] , "expireTime" => $time_exp['date']), "uid = '" . $account[0]['uid'] . "'") ){
					$this->result['errCode'] = 0x0               ;
					$this->result['errMsg'] = "";
					$this->result['uid'] = $account[0]['uid'];
					$this->result['name'] = $account[0]['name'];
					$this->result['email'] = $account[0]['email'];
					$this->result['username'] = $account[0]['username'];
					$this->result['picture'] = $account[0]['picture'];
					$this->result['token'] = $acc_token;
					$this->result['time_exp'] = $time_exp;
				} else {
					$this->result['errCode'] = 12;
					$this->result['errMsg'] = "Update Account Token Error";
				}
			} else {
				$this->result['errCode'] = 11;
				$this->result['errMsg'] = "username or password error";
			}
		}
		echo CJSON::encode($this->result);
	}

	/*
	 * Function API loginWithToken
	*/

	public function actionloginWithToken () {
		if ( isset($_GET['token'])) {
			$token = $_GET['token'];
			if ( AccountToken::model()->count("token = '" . $token . "' ") == 0 ){
				$this->result['errCode'] = 0xA;
				$this->result['errMsg'] = "this token no in database.";
			} else {
				$newToken = Helper::genToken();
				$newDate = Helper::DateTimeAdd(1);
				$acc_id = AccountToken::model()->findAll("token = '" . $token . "'");

			}
		} else {
			$this->result['errCode'] = 0xA;
			$this->result['errMsg'] = "token Undefined variable.";
		}
	}

	/*
	 * Function API Get Like
	*/

	public function actiongetLike() {
		if ( isset($_GET['id'])) {
			$id = $_GET['id'];
			if ( LikeGroup::model()->count("like_group_id = :id", array(':id'=> $id)) == 0 ) {
				$group = new LikeGroup();
				$group->like_group_id = $id;
				$group->save();
				/*
				$this->result['errCode'] = 14;
				$this->result['errMsg'] = $id." like id no data";
				/*
				 */
			} else {
				$model = LikeGroup::model()->with(array('like'))->findAll("like_group_id = :id", array(':id'=> $id));
				$this->result['errCode'] = 0;
				$this->result['errMsg'] = "";
				$result = $model;
				foreach ( $result as $key => $value ) {
					foreach ( $value->like as $keyz => $valuez ) {
						//$this->result[$key]['like_id'] = $result[$key]['like_id'];
						$this->result[$key]['createTime'] = $result[$key]['createTime'];
						$this->result[$key]['like_group_id'] = $result[$key]['like_group_id'];
						$this->result[$key]['like'][$keyz]['uid'] = $valuez['uid'];
						$this->result[$key]['like'][$keyz]['name'] = $valuez['name'];
					}
				}
			}
		} else {
			$this->result['errCode'] = 13;
			$this->result['errMsg'] = "like id Undefined variable.";
		}
		echo CJSON::encode($this->result);
	}
	
	/*
	 * Function API Get Photo Group Detail
	*/

	public function actiongetphotoGroup() {
		if ( isset($_GET['id'])) {
			$id = $_GET['id'];
			if (PhotoGroup::model()->count("photo_group_id = '" . $id . "'") == 0 ) {
				$this->result['errCode'] = 16;
				$this->result['errMsg'] = $id." Photo Group id no data";
			} else {
				$model = PhotoGroup::model()->with('account','photo'  )->findAll("photo_group_id = '" . $id . "' ");
				$this->result['errCode'] = 0x0;
				$this->result['errMsg'] = "";
				$this->result['photo_group_id'] = $model[0]['photo_group_id'];
				$this->result['photo_count'] = $model[0]['photo_count'];
				$this->result['account']['uid'] = $model[0]['account']['uid'];
				$this->result['account']['name'] = $model[0]['account']['name'];
				$this->result['createTime'] = $model[0]['createTime'];
				$this->result['photo']  = $model[0]['photo'];
			}
		} else {
			$this->result['errCode'] = 15;
			$this->result['errMsg'] = "Photo Group id Undefined variable.";
		}
		echo CJSON::encode($this->result);
	}

	/*
	 * Function API Get Comment
	*/

	public function actiongetCommentGroup() {
		if ( isset($_GET['id'])) {
			$id = $_GET['id'];
			if (CommentGroup::model()->count("comment_group = '" . $id . "'") == 0 ) {
				$this->result['errCode'] = 18;
				$this->result['errMsg'] = $id." Comment Group id no data";
			} else {
				$model = CommentGroup::model()->with(array('comment' => array('with'=> 'account')))->findAll("coumment_group = '" . $id . "' ");
				$this->result['errCode'] = 0x0;
				$this->result['errMsg'] = "";
				$result = $model;
				foreach ( $result as $key => $value ) {
					foreach ( $value->comment as $keyz => $valuez ) {
						$this->result['errCode'] = 0x0;
						$this->result['errMsg'] = "";
						$this->result[$key]['comment_group_auto_id'] = $result[$key]['id'];
						$this->result[$key]['createTime'] = $result[$key]['createTime'];
						$this->result[$key]['comment_group_id'] = $result[$key]['comment_group'];
						$this->result[$key]['owner_id'] = $result[$key]['uid'];
						$this->result[$key]['count'] = $result[$key]['count'];
						$this->result[$key]['comment'][$keyz]['uid'] = $valuez['uid'];
						$this->result[$key]['comment'][$keyz]['name'] = $valuez->account['name'];
						$this->result[$key]['comment'][$keyz]['comment_text'] = $valuez['comment_text'];
						$this->result[$key]['comment'][$keyz]['comment_time'] = $valuez['comment_time'];
						$this->result[$key]['comment'][$keyz]['like'] = $valuez['like'];
					}
				}
			}
		} else {
			$this->result['errCode'] = 17;
			$this->result['errMsg'] = "Comment Group id Undefined variable.";
		}
		echo CJSON::encode($this->result);
	}

	/*
	 * Function API Get User
	*/
	public function actiongetUser(){
		if (isset($_GET['id'])) {
			$id = $_GET['id'];
			if (Account::model()->count("uid = '" . $id . "' ") == 0 ) {
				$this->result['errCode'] = 20;
				$this->result['errMsg'] = $id." User id no data";
			} else {
				$model = Account::model()->with('accountDetail')->findByPK($id);
				$result = $model;
				$this->result['errCode'] = 0x0;
				$this->result['errMsg'] = "";
				$this->result['account']['uid'] = $result['uid'];
				$this->result['account']['name'] = $result['name'];
				$this->result['account']['email'] = $result['email'];
				$this->result['account']['createTime'] = $result['createTime'];
				$this->result['account']['id_type'] = $result['id_type'];
				$this->result['account']['confirm_email'] = $result['confirm_email'];
				$this->result['account']['confirm_phone'] = $result['confirm_phone'];
				$this->result['account']['picture'] = $result['picture'];
				$this->result['account']['facebook'] = $result['facebook'];
				$this->result['account']['accountDetail'] = $result['accountDetail'];
			}
		} else {
			$this->result['errCode'] = 19;
			$this->result['errMsg'] = "Get User id Undefined variable.";
		}
		echo CJSON::encode($this->result);
	}

	/*
	 * Function API Get User Facebook
	*/

	public function actiongetUserFacebook() {
		if ( isset($_GET['id'])) {
			$id = $_GET['id'];
			if ( Facebook::model()->count("uid = '" . $id . "' ") == 0 ) {
				$this->result['errCode'] = 22;
				$this->result['errMsg'] = $id." this User id no facebook data";
			} else {
				$result = Facebook::model()->findAll("uid = '" . $id . "' ");
				$this->result['data'] = $result;
				$this->result['errCode'] = 0x0;
				$this->result['errMsg'] = "";
			}
		} else {
			$this->result['errCode'] = 21;
			$this->result['errMsg'] = "facebook id Undefined variable.";
		}
		echo CJSON::encode($this->result);
	}

	/*
	 * Function API Get Account Token Detail
	*/

	public function actiongetUserToken() {
		if ( isset($_GET['id'])) {
			$id = $_GET['id'];
			if ( AccountToken::model()->count("uid = '" . $id . "' ") == 0 ) {
				$this->result['errCode'] = 24;
				$this->result['errMsg'] = $id." this uid no token data";
			} else {
				$this->result['data'] = AccountToken::model()->findAll("uid = '" . $id . "'");
				$this->result['errCode'] = 0x0;
				$this->result['errMsg'] = "";
			}
		} else {
			$this->result['errCode'] = 23;
			$this->result['errMsg'] = "Get User token id Undefined variable.";
		}
		echo CJSON::encode($this->result);
	}

	/*
	 * Function API Get user album list
	*/

	public function actiongetUserAlbum() {
		if ( isset($_GET['id'])) {
			$id = $_GET['id'];
			if ( Album::model()->count("uid = '" . $id . "' ") == 0 ) {
				$this->result['errCode'] = 26;
				$this->result['errMsg'] = $id." this album id no data";
			} else {
				$this->result['data'] = Album::model()->findAll("uid = '" . $id . "'");
				$this->result['errCode'] = 0x0;
				$this->result['errMsg'] = "";
			}
		} else {
			$this->result['errCode'] = 25;
			$this->result['errMsg'] = "getUserAlbum Undefined variable.";
		}
		echo CJSON::encode($this->result);
	}

	/*
	 * Function API Get Site Gallery
	*/
	public function actiongetSiteGallery() {
		if ( isset($_GET['id'])) {
			$id = $_GET['id'];
			if ( Gallery::model()->count("place_id = '" . $id . "' ") == 0 ) {
				$this->result['errCode'] = 28;
				$this->result['errMsg'] = $id." this SiteGallery no data";
			} else {
				$this->result['data'] = Gallery::model()->findAll("place_id = '" . $id . "'");
				$this->result['errCode'] = 0x0;
				$this->result['errMsg'] = "";
			}
		} else {
			$this->result['errCode'] = 27;
			$this->result['errMsg'] = "getSiteGallery Undefined variable.";
		}
		echo CJSON::encode($this->result);
	}

	/*
	 * Function API Get Site Info
	*/

	public function actiongetSiteInfo() {
		if ( isset($_GET['id'])) {
			$id = $_GET['id'];
			if ( Place::model()->count("place_id = '" . $id . "' ") == 0 ) {
				$this->result['errCode'] = 30;
				$this->result['errMsg'] = $id." this Site Info no data";
			} else {
				$data = Place::model()->with('Site')->findByAttributes(array("place_id" => $id));
				$data = $data->getAttributes();
				$this->result['data'] = array();
				$this->result['data']['id'] = $data['place_id'];
				$this->result['data']['name'] = $data['name'];
				$this->result['data']['lat'] = $data['lat'];
				$this->result['data']['lng'] = $data['lng'];
				$this->result['data']['like'] = $data['like'];
				$this->result['data']['owner_id'] = $data['owner_id'];

				$this->result['data']['rateAll'] = $this->getRateAll($data['place_id']);

				$total = 0;
				$reviews = Review::model()->findAllByAttributes(array("place_id" => $data['place_id']));
				foreach($reviews as $key => $value){
					$total += $value['rate'];
				}

				$this->result['data']['avgRate'] = $total/count($reviews);
				$this->result['errCode'] = 0x0;
				$this->result['errMsg'] = "";
			}
		} else {
			$this->result['errCode'] = 29;
			$this->result['errMsg'] = "getSiteInfo Undefined variable.";
		}
		echo CJSON::encode($this->result);
	}

	/*
	 * Function API Like
	*/

	public function actionLike() {
		if ( isset($_GET['id']) and isset($_GET['uid'])) {
			$id = $_GET['id'];
			$uid = $_GET['uid'];
			if (Helper::checkUser($uid)) {
				/*
				 if ( LikeGroup::model()->count("like_group_id = '" . $id . "'") == 0 ) {
				$model = new LikeGroup;
				$lastLikeGroup = LikeGroup::model()->findAll(array('order'=>'like_group_id'));
				$idGroup = $lastLikeGroup[0]['like_group_id']+1;
				$model->like_group_id = $idGroup;
				if ($model->save()) {
				if (Like::model()->count("like_group = '" . $id . "' and uid = '" . $uid . "'") == 0 ) {
				$model = new Like;
				$model->like_group = $id;
				$model->uid = $uid;
				if ($model->save()) {
				$this->result['data']['like_id'] = $model->like_id;
				$this->result['data']['like_group'] = $id;
				$this->result['data']['uid'] = $uid;
				$this->result['data']['like_time'] = $model->like_time;
				$this->result['errCode'] = 0;
				$this->result['errMsg'] = "";
				} else {
				$this->result['errCode'] = "0xF";
				$this->result['errMsg'] = "Save Like to Database Server Error.";
				}
				} else {
				$this->result['errCode'] = "0x21";
				$this->result['errMsg'] = "You have already been done";
				}
				} else {
				$this->result['errCode'] = "0x23";
				$this->result['errMsg'] = "Save LikeGroup to Database Server Error.";
				}
				} else {
				if (Like::model()->count("like_group = '" . $id . "' and uid = '" . $uid . "'") == 0 ) {
				$model = new Like;
				$model->like_group = $id;
				$model->uid = $uid;
				if ($model->save()) {
				$this->result['data']['like_id'] = $model->like_id;
				$this->result['data']['like_group'] = $id;
				$this->result['data']['uid'] = $uid;
				$this->result['data']['like_time'] = $model->like_time;
				$this->result['errCode'] = 0;
				$this->result['errMsg'] = "";
				} else {
				$this->result['errCode'] = "0xF";
				$this->result['errMsg'] = "Save Like to Database Server Error.";
				}
				} else {
				$this->result['errCode'] = "0x21";
				$this->result['errMsg'] = "You have already been done";
				}
				}*/
				if (Like::model()->count("like_group = '" . $id . "' and uid = '" . $uid . "'") == 0 ) {
				$model = new Like;
				$model->like_group = $id;
				$model->uid = $uid;
				if ($model->save()) {
					$this->result['data']['like_id'] = $model->like_id;
					$this->result['data']['like_group'] = $id;
					$this->result['data']['uid'] = $uid;
					$this->result['data']['like_time'] = $model->like_time;
					$this->result['errCode'] = 0x0;
					$this->result['errMsg'] = "";
				} else {
					$this->result['errCode'] = 34;
					$this->result['errMsg'] = "Save Like to Database Server Error.";
				}
			} else {
				$this->result['errCode'] = 33;
				$this->result['errMsg'] = "You have already been done";
			}
			} else {
				$this->result['errCode'] = 0x20;
				$this->result['errMsg'] = "This No User Database Server .";
			}
		} else {
			$this->result['errCode'] = 31;
			$this->result['errMsg'] = "Like id and uid Undefined variable.";
		}
		echo CJSON::encode($this->result);
	}

	/*
	 * Function API unLike
	*/

	public function actionunLike() {
		if ( isset($_GET['uid']) and isset($_GET['like_id'])) {
			$uid = $_GET['uid'];
			$like_id = $_GET['like_id'];
			if (Like::model()->count("like_id = '" . $like_id . "' and uid = '" . $uid . "'") == 0 ) {
				$post = Like::model()->findByPk($like_id);
				if ($post->delete()){
					$this->result['errCode'] = 0x0;
					$this->result['errMsg'] = "";
					$this->result['data'] = "Deleting ok!";
				} else {
					$this->result['errCode'] = 40;
					$this->result['errMsg'] = "Deleting Like id in Database Server Error.";
				}
			} else {
				$this->result['errCode'] = 39;
				$this->result['errMsg'] = "no Like id in Database Server.";
			}
		} else {
			$this->result['errCode'] = 38;
			$this->result['errMsg'] = "unLike Undefined variable.";
		}
		echo CJSON::encode($this->result);
	}

	/*
	 * Function API Add review site
	*/

	public function actionaddReviewSite() {
		if (isset($_GET['uid']) and isset($_GET['place_id']) and isset($_GET['rate']) and isset($_GET['text'])) {
			$uid = $_GET['uid'];
			$place_id = $_GET['place_id'];
			$rate = $_GET['rate'];
			$text = $_GET['text'];
			if (Helper::checkUser($uid)) {
				if (Helper::checkSite($place_id)) {
					if (Review::model()->count("place_id = '" . $place_id . "' and uid = '" . $uid . "'") == 0 ) {

						$photo_group = new PhotoGroup();
						$photo_group->uid = $uid;
						$photo_group->save();
						 
						$model = new Review;
						$model->uid = $uid;
						$model->place_id = $place_id;
						$model->rate = $rate;
						$model->text = $text;
						$model->photo_group = $photo_group->photo_group_id;
						if ($model->save()) {
							$this->result['errCode'] = 0x0;
							$this->result['errMsg'] = "";
							$this->result['data']['review_id'] = $model->id;
							$this->result['data']['place_id'] = $place_id;
							$this->result['data']['rate'] = $rate;
							$this->result['data']['text'] = $text;
						} else {
							$this->result['errCode'] = 36;
							$this->result['errMsg'] = "Save addReviewSite to Database Server Error.";
						}
						$this->result['data']['images'] = null;
						if(isset($_GET['photo'])){
							$photo = CJSON::decode($_GET['photo']);
							$images = array();
							foreach($photo as $key => $value) {
								$photoModel[$key] = new Photo();
								$images[$key]['url'] = $photoModel[$key]->photo_url = $value['name'];
								$photoModel[$key]->photo_group = $photo_group->photo_group_id;
								$photoModel[$key]->save();
								$images[$key]['id'] = $photoModel[$key]->photo_id;
							}
							$this->result['data']['images'] = $images;
							$photo_group->photo_count = count($images);
							$photo_group->save();
						}
					} else {
						$photo_group = new PhotoGroup();
						$photo_group->uid = $uid;
						$photo_group->save();
						 
						if ( Review::model()->updateAll(array("text" => $text, "rate"=> $rate, 'photo_group'=> $photo_group->photo_group_id), "uid = '" . $uid . "' and place_id = '" . $place_id . "'") ){
							$review_id = Review::model()->findAll("uid = '" . $uid . "' and place_id = '" . $place_id . "'");
							$this->result['errCode'] = 0x0;
							$this->result['errMsg'] = "";
							$this->result['data']['review_id'] = $review_id[0]['id'];
							$this->result['data']['place_id'] = $place_id;
							$this->result['data']['rate'] = $rate;
							$this->result['data']['text'] = $text;
						} else {
							$this->result['errCode'] = 37;
							$this->result['errMsg'] = "Update Review Site Error";
						}
						$this->result['data']['images'] = null;
						if(isset($_GET['photo'])){
							$photo = CJSON::decode($_GET['photo']);
							$images = array();
							foreach($photo as $key => $value) {
								$photoModel[$key] = new Photo();
								$images[$key]['url'] = $photoModel[$key]->photo_url = $value['name'];
								$photoModel[$key]->photo_group = $photo_group->photo_group_id;
								$photoModel[$key]->save();
								$images[$key]['id'] = $photoModel[$key]->photo_id;
							}
							$this->result['data']['images'] = $images;
							$photo_group->photo_count = count($images);
							$photo_group->save();
						}
					}
				} else {
					$this->result['errCode'] = 35;
					$this->result['errMsg'] = "No This Place Site Database Server .";
				}
			} else {
				$this->result['errCode'] = 32;
				$this->result['errMsg'] = "This No User Database Server .";
			}
		} else {
			$this->result['errCode'] = 0x22;
			$this->result['errMsg'] = "addReviewSite Undefined variable.";
		}
		if($this->result['errCode'] == 0){
			$this->result['data']['rateAll'] = $this->getRateAll($this->result['data']['place_id']);
		}
		echo CJSON::encode($this->result);
	}

	/*
	 * Function API useful yes
	*/

	public function actionUsefulYes() {
		if (isset($_GET['uid']) and isset($_GET['review_id'])){
			$uid = $_GET['uid'];
			$review_id = $_GET['review_id'];
			if (Helper::checkUser($uid)) {
				if (ReviewUseful::model()->count("review_id = '" . $review_id . "' and uid = '" . $uid . "'") == 0 ) {
					$model = new ReviewUseful;
					$model->uid = $uid;
					$model->review_id = $review_id;
					$model->type = "yes";
					if ($model->save()) {
						$this->result['errCode'] = 0x0;
						$this->result['errMsg'] = "";
						$this->result['data']['review_useful_id'] = $model->id;
						$this->result['data']['uid'] = $uid;
						$this->result['data']['review_id'] = $review_id;
						$this->result['data']['count'] = ReviewUseful::model()->count("review_id = '" . $review_id . "' and type = 'yes'");
					} else {
						$this->result['errCode'] = 0x2A;
						$this->result['errMsg'] = "insert useful yes Site Error";
					}
				} else {
					$modelUpdate = ReviewUseful::model()->findByAttributes(array(
							'uid'=> $uid,
							'review_id'=> $review_id
					));
					$modelUpdate->type = "yes";
					if ($modelUpdate->save()) {
						$review_useful_id = ReviewUseful::model()->findAll("review_id = '" . $review_id . "' and uid = '" . $uid . "'");
						$this->result['errCode'] = 0x0;
						$this->result['errMsg'] = "";
						$this->result['data']['review_useful_id'] = $review_useful_id;
						$this->result['data']['uid'] = $uid;
						$this->result['data']['review_id'] = $review_id;
						$this->result['data']['count'] = ReviewUseful::model()->count("review_id = '" . $review_id . "' and type = 'yes'");
					} else {
						$this->result['errCode'] = 42;
						$this->result['errMsg'] = "Update Review useful type Error";
					}
				}

				$review = Review::model()->findByPk($review_id);
				$review->yes = ReviewUseful::model()->count("review_id = '" . $review_id . "' and type = 'yes'");
				$review->no = ReviewUseful::model()->count("review_id = '" . $review_id . "' and type = 'no'");
				if(!$review->save()) {
					$this->result['errCode'] = 61;
					$this->result['errMsg'] = "Update review useful count Error.";
				}
			} else {
				$this->result['errCode'] = 32;
				$this->result['errMsg'] = "This No User Database Server .";
			}
		} else {
			$this->result['errCode'] = 41;
			$this->result['errMsg'] = "usefulYes Undefined variable.";
		}
		echo CJSON::encode($this->result);
	}

	/*
	 * Function API useful no
	*/

	public function actionUsefulNo() {
		if (isset($_GET['uid']) and isset($_GET['review_id'])){
			$uid = $_GET['uid'];
			$review_id = $_GET['review_id'];
			if (Helper::checkUser($uid)) {
				$review = Review::model()->findByPk($review_id);
				if (ReviewUseful::model()->count("review_id = '" . $review_id . "' and uid = '" . $uid . "'") == 0 ) {
					$model = new ReviewUseful;
					$model->uid = $uid;
					$model->review_id = $review_id;
					$model->type = "no";
					if ($model->save() && $review->save()) {
						$this->result['errCode'] = 0x0;
						$this->result['errMsg'] = "";
						$this->result['data']['review_useful_id'] = $model->id;
						$this->result['data']['uid'] = $uid;
						$this->result['data']['review_id'] = $review_id;
						$this->result['data']['count'] = ReviewUseful::model()->count("review_id = '" . $review_id . "' and type = 'no'");
					} else {
						$this->result['errCode'] = 44;
						$this->result['errMsg'] = "insert useful no Site Error";
					}
				} else {
					$modelUpdate = ReviewUseful::model()->findByAttributes(array(
							'uid'=> $uid,
							'review_id'=> $review_id
					));
					$modelUpdate->type = "no";
					$review['yes']--;
					$review['no']++;
					if ($modelUpdate->save() && $review->save()) {
						$review_useful_id = ReviewUseful::model()->findAll("review_id = '" . $review_id . "' and uid = '" . $uid . "'");
						$this->result['errCode'] = 0x0;
						$this->result['errMsg'] = "";
						$this->result['data']['review_useful_id'] = $review_useful_id;
						$this->result['data']['uid'] = $uid;
						$this->result['data']['review_id'] = $review_id;
						$this->result['data']['count'] = ReviewUseful::model()->count("review_id = '" . $review_id . "' and type = 'no'");
					} else {
						$this->result['errCode'] = 42;
						$this->result['errMsg'] = "Update Review useful type Error";
						foreach ( $main as $key => $value ) {
							$account = Account::model()->findAll("uid = '" . $value['uid'] . "' ");
							$this->result[$key]['account']['uid'] = $account[0]['uid'];
							$this->result[$key]['account']['name'] = $account[0]['name'];
							$this->result[$key]['account']['email'] = $account[0]['email'];
							$this->result[$key]['review_id'] = $value['id'];
							$this->result[$key]['text'] = $value['text'];
							$this->result[$key]['time'] = $value['time'];
							$this->result[$key]['yes'] = $value['yes'];
							$this->result[$key]['no'] = $value['no'];
							$getYes = ReviewUseful::model()->findAll("review_id = '" . $value['id'] . "' and type = 'yes'");
							foreach ( $getYes as $a => $b ) {
								$this->result[$key]['yesUser'][$a]['uid'] = $b['uid'];
								$this->result[$key]['yesUser'][$a]['createTime'] = $b['createTime'];
								$this->result[$key]['yesUser'][$a]['review_useful_id'] = $b['id'];
								$f = Account::model()->findAllByPk($b['uid']);
								$this->result[$key]['yesUser'][$a]['name'] = $f[0]['name'];
							}
							$getNo = ReviewUseful::model()->findAll("review_id = '" . $value['id'] . "' and type = 'no'");
							foreach ( $getNo as $a => $b ) {
								$this->result[$key]['noUser'][$a]['uid'] = $b['uid'];
								$this->result[$key]['noUser'][$a]['createTime'] = $b['createTime'];
								$this->result[$key]['noUser'][$a]['review_useful_id'] = $b['id'];
								$f = Account::model()->findAllByPk($b['uid']);
								$this->result[$key]['noUser'][$a]['name'] = $f[0]['name'];
							}
							if ( ReviewUseful::model()->count("review_id = '" . $value['id'] . "' and uid = '" . $uid . "'") == 0 ) {
								$this->result[$key]['user_status'] = 0;
							} else {
								$userStatus = ReviewUseful::model()->findAll("review_id = '" . $value['id'] . "' and uid = '" . $uid . "'");
								if ( $userStatus[0]['type'] == 'yes' ) {
									$this->result[$key]['user_status'] = "yes";
								} else {
									$this->result[$key]['user_status'] = "no";
								}
							}
						}
					}
				}

				$review = Review::model()->findByPk($review_id);
				$review->yes = ReviewUseful::model()->count("review_id = '" . $review_id . "' and type = 'yes'");
				$review->no = ReviewUseful::model()->count("review_id = '" . $review_id . "' and type = 'no'");
				if(!$review->save()) {
					$this->result['errCode'] = 61;
					$this->result['errMsg'] = "Update review useful count Error.";
				}
			} else {
				$this->result['errCode'] = 32;
				$this->result['errMsg'] = "This No User Database Server .";
			}
		} else {
			$this->result['errCode'] = 43;
			$this->result['errMsg'] = "usefulNo Undefined variable.";
		}
		echo CJSON::encode($this->result);
	}

	/*
	 * Function API useful Deleting
	*/

	public function actionUsefulDel() {
		if (isset($_GET['uid']) and isset($_GET['useful_id'])) {
			$uid = $_GET['uid'];
			$useful_id = $_GET['useful_id'];
			if (ReviewUserful::model()->count("id = '" . $useful_id . "' and uid = '" . $uid . "'") == 0 ) {
				$post = ReviewUserful::model()->findByPk($useful_id);
				if ($post->delete()){
					$this->result['errCode'] = 0x0;
					$this->result['errMsg'] = "";
					$this->result['data'] = "Deleting ok!";
				} else {
					$this->result['errCode'] = 46;
					$this->result['errMsg'] = "Deleting useful review Database Server Error.";
				}
			} else {
				$this->result['errCode'] = 39;
				$this->result['errMsg'] = "no Like id in Database Server.";
			}
		} else {
			$this->result['errCode'] = 45;
			$this->result['errMsg'] = "usefulDel Undefined variable.";
		}
		echo CJSON::encode($this->result);
	}

	/*
	 * Function API Get Review
	*/

	public function actiongetReview(){
		if ( isset($_GET['place_id']) ) {
			if (isset($_GET['uid'])) {
				$uid = $_GET['uid'];
			} else {
				$uid = 0;
			}
			$place_id = $_GET['place_id'];
			if (Helper::checkSite($place_id)) {
				if (isset($_GET['type'])) {
					$type = $_GET['type'];
				} else {
					$options = array();
					if(isset($_GET['order'])){
						if($_GET['order'] == 'popular') {
							$options['order'] = '`yes`/ (`no` or 1) DESC';
						}
						else if($_GET['order'] == 'recent') {
							$options['order'] = '`time` DESC';
						}
					}
					$main = Review::model()->findAllByAttributes(array("place_id"=> $place_id), $options);
					$this->result['errCode'] = 0x0;
					$this->result['errMsg'] = "";
					foreach ( $main as $key => $value ) {
						$account = Account::model()->findAll("uid = '" . $value['uid'] . "' ");
						$this->result[$key]['account']['uid'] = $account[0]['uid'];
						$this->result[$key]['account']['name'] = $account[0]['name'];
						$this->result[$key]['account']['email'] = $account[0]['email'];
						$this->result[$key]['review_id'] = $value['id'];
						$this->result[$key]['text'] = $value['text'];
						$this->result[$key]['time'] = $value['time'];
						$this->result[$key]['yes'] = $value['yes'];
						$this->result[$key]['no'] = $value['no'];
						$this->result[$key]['rate'] = $value['rate'];
						$getYes = ReviewUseful::model()->findAll("review_id = '" . $value['id'] . "' and type = 'yes'");
						foreach ( $getYes as $a => $b ) {
							$this->result[$key]['yesUser'][$a]['uid'] = $b['uid'];
							$this->result[$key]['yesUser'][$a]['createTime'] = $b['createTime'];
							$this->result[$key]['yesUser'][$a]['review_useful_id'] = $b['id'];
							$f = Account::model()->findAllByPk($b['uid']);
							$this->result[$key]['yesUser'][$a]['name'] = $f[0]['name'];
						}
						$getNo = ReviewUseful::model()->findAll("review_id = '" . $value['id'] . "' and type = 'no'");
						foreach ( $getNo as $a => $b ) {
							$this->result[$key]['noUser'][$a]['uid'] = $b['uid'];
							$this->result[$key]['noUser'][$a]['createTime'] = $b['createTime'];
							$this->result[$key]['noUser'][$a]['review_useful_id'] = $b['id'];
							$f = Account::model()->findAllByPk($b['uid']);
							$this->result[$key]['noUser'][$a]['name'] = $f[0]['name'];
						}
						if ( ReviewUseful::model()->count("review_id = '" . $value['id'] . "' and uid = '" . $uid . "'") == 0 ) {
							$this->result[$key]['user_status'] = 0;
						} else {
							$userStatus = ReviewUseful::model()->findAll("review_id = '" . $value['id'] . "' and uid = '" . $uid . "'");
							if ( $userStatus[0]['type'] == 'yes' ) {
								$this->result[$key]['user_status'] = "yes";
							} else {
								$this->result[$key]['user_status'] = "no";
							}
						}

						$this->result[$key]['images'] = null;
						if($value['photo_group'] != null){
							$this->result[$key]['images'] = array();
							 
							$images = Photo::model()->findAllByAttributes(array('photo_group'=> $value['photo_group']));
							 
							foreach($images as $a => $b){
								$this->result[$key]['images'][$a] = array(
										'url'=> $b['photo_url'],
										'id'=> $b['photo_id'],
								);
							}
							 
						}
					}
				}
			} else {
				$this->result['errCode'] = 35;
				$this->result['errMsg'] = "No This Place Site Database Server .";
			}
		} else {
			$this->result['errCode'] = 47;
			$this->result['errMsg'] = "getReview place_id Undefined variable.";
		}
		echo CJSON::encode($this->result);
	}

	/*
	 * Add Tab Site
	*/

	public function actionAddTabSite() {
		if ( isset($_GET['place_id']) and isset($_GET['name']) and isset($_GET['type']) and isset($_GET['uid']) ) {
			$place_id = $_GET['place_id'];
			$name = $_GET['name'];
			$type = $_GET['type'];
			$uid =$_GET['uid'];
			if ( Helper::checkUser($uid)) {
				if ( Helper::checkSite($place_id) ) {
					if ( Helper::checkOwnerSite($uid,$place_id)) {
						$max = Tab::model()->findAll(array( "condition"=>"place_id = '" . $place_id . "'" , 'order'=>'seq DESC'));
						if ( $max == null ) {
							$x = 1;
						} else {
							$x = CJSON::decode($max[0]['seq'])+1;
						}
						$tab = new Tab;
						$tab->place_id = $place_id;
						$tab->name = $name;
						$tab->type = $type;
						$tab->seq = $x;
						if ($tab->save()) {
							$this->result['errCode'] = 0x0;
							$this->result['errMsg'] = "";
							$this->result['data']['tab_id'] = $tab->id;
							$this->result['data']['name'] = $name;
							$this->result['data']['type'] = $type;
						} else {
							$this->result['errCode'] = 50;
							$this->result['errMsg'] = "Add Tab Site Save to database error";
						}
					} else {
						$this->result['errCode'] = 49;
						$this->result['errMsg'] = "uid no owner this place";
					}
				} else {
					$this->result['errCode'] = 35;
					$this->result['errMsg'] = "No This Place Site Database Server .";
				}
			} else {
				$this->result['errCode'] = 32;
				$this->result['errMsg'] = "This No User Database Server .";
			}
		} else {
			$this->result['errCode'] = 48;
			$this->result['errMsg'] = "AddTabSite Undefined variable.";
		}
		echo CJSON::encode($this->result);
	}

	/*
	 * Edit Tab Site
	*/

	public function actionEditTabSite() {
		if ( isset($_GET['tabid']) and isset($_GET['place_id']) and isset($_GET['name']) and isset($_GET['type']) and isset($_GET['uid']) ) {
			$uid = $_GET['uid'];
			$place_id = $_GET['place_id'];
			$name = $_GET['name'];
			$type = $_GET['type'];
			$tabid = $_GET['tabid'];
			if (Helper::checkUser($uid)) {
				if ( Helper::checkSite($place_id)) {
					if ( Helper::checkOwnerSite($uid,$place_id)) {
						if (Tab::model()->count("id = '" . $tabid . "'") == 0 ) {
							$this->result['errCode'] = 52;
							$this->result['errMsg'] = "No Tab id in Database";
						} else {
							if (Tab::model()->updateAll(array("name"=>$name, "type"=>$type ), "id = '" . $tabid . "'")) {
								$this->result['errCode'] = 0x0;
								$this->result['errMsg'] = "";
								$this->result['status'] = "Save ok";
							} else {
								$this->result['errCode'] = 53;
								$this->result['errMsg'] = "Update Tab in Database Error";
							}
						}
					} else {
						$this->result['errCode'] = 49;
						$this->result['errMsg'] = "uid no owner this place";
					}
				} else {
					$this->result['errCode'] = 35;
					$this->result['errMsg'] = "No This Place Site Database Server .";
				}
			} else {
				$this->result['errCode'] = 32;
				$this->result['errMsg'] = "This No User Database Server .";
			}
		} else {
			$this->result['errCode'] = 51;
			$this->result['errMsg'] = "EditTabSite Undefined variable.";
		}
		echo CJSON::encode($this->result);
	}
    /*
     * Upload Profile Photo
     * */
    public function actionuploadprofilephoto() {
        $uid = $_POST['uid'];
        $uploaddir = './uploads/';
        $ext = end(explode(".", $_FILES["file"]["name"]));//gets extension
        $file = $uid.".".$ext;
        $uploadfile = $uploaddir . $file;
        $thumb_dir = './uploads/160/';
        $thumb640_dir = './uploads/640/';
        $thumb_name = $uid.".".$ext;
        if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile)) {
            chmod($uploadfile,0777);
            Helper::SaveThumbnail($uploadfile , $thumb_dir . $file, 160, 160);
            chmod($thumb_dir.$thumb_name,0777);
            echo "http://115.178.63.161/uploads/{$file}";

            // Max vert or horiz resolution
            $maxsize = 1200;

            // create new Imagick object
            $image = new Imagick($uploadfile);

            // Resizes to whichever is larger, width or height
            if($image->getImageHeight() <= $image->getImageWidth())
            {
                // Resize image using the lanczos resampling algorithm based on width
                $image->resizeImage($maxsize,0,Imagick::FILTER_LANCZOS,1);
            }
            else
            {
                // Resize image using the lanczos resampling algorithm based on height
                $image->resizeImage(0,$maxsize,Imagick::FILTER_LANCZOS,1);
            }

            // Set to use jpeg compression
            $image->setImageCompression(Imagick::COMPRESSION_JPEG);

            // Set compression level (1 lowest quality, 100 highest quality)
            $image->setImageCompressionQuality(75);
            // Strip out unneeded meta data
            $image->stripImage();
            // Writes resultant image to output directory
            $image->writeImage($file);
            // Destroys Imagick object, freeing allocated resources in the process
            $image->destroy();
            chmod($file, 0777);

            // 320 Show Preview
            $immid = new Imagick($file);
            if ( $immid->getimagewidth() > 640 ) {
                $immid->thumbnailImage(640,null);
                $immid->writeImage(Yii::app()->request->baseUrl.$thumb640_dir.$thumb_name);
                $immid->destroy();
                chmod(Yii::app()->request->baseUrl.$thumb640_dir.$thumb_name, 0777);
            } else {
                $immid->writeImage(Yii::app()->request->baseUrl.$thumb640_dir.$thumb_name);
                $immid->destroy();
                chmod(Yii::app()->request->baseUrl.$thumb640_dir.$thumb_name, 0777);
            }


        } else {
            echo "error";
        }

    }

	/*
	 * Del Tab Site
	*/

	public function actionDelTabSite() {
		if ( isset($_GET['tabid']) and isset($_GET['uid']) and isset($_GET['place_id'])) {
			$uid = $_GET['uid'];
			$tabid = $_GET['tabid'];
			$place_id = $_GET['place_id'];
			if ( Helper::checkUser($uid)) {
				if ( Helper::checkSite($place_id)) {
					if ( Helper::checkOwnerSite($uid,$place_id)) {
						$post = Tab::model()->findByPk($tabid);
						if ($post->delete()){
							$this->result['errCode'] = 0x0;
							$this->result['errMsg'] = "";
							$this->result['data'] = "Deleting ok!";
						} else {
							$this->result['errCode'] = 55;
							$this->result['errMsg'] = "Del Tab Site Error";
						}
					} else {
						$this->result['errCode'] = 49;
						$this->result['errMsg'] = "uid no owner this place";
					}
				} else {
					$this->result['errCode'] = 35;
					$this->result['errMsg'] = "No This Place Site Database Server .";
				}
			} else {
				$this->result['errCode'] = 32;
				$this->result['errMsg'] = "This No User Database Server .";
			}
		} else {
			$this->result['errCode'] = 54;
			$this->result['errMsg'] = "DelTabSite Undefined variable.";
		}
		echo CJSON::encode($this->result);
	}

	/*
	 * Get Tab Site
	*/

	public function actiongetTabSite() {
		if (isset($_GET['place_id'])) {
			$place_id = $_GET['place_id'];
			if ( Tab::model()->count("place_id = '" . $place_id . "'") == 0 ) {
				$this->result['errCode'] = 58;
				$this->result['errMsg'] = "place id no tab";
			} else {
				$tab = Tab::model()->findAll(array("condition" => "place_id = '" . $place_id . "'" , 'order'=>'seq ASC'));
				$result = $tab;
				$this->result['errCode'] = 0x0;
				$this->result['errMsg'] = "";
				foreach ( $result as $key => $value ) {
					$this->result['data'][$key]['id'] = $value['id'];
					$this->result['data'][$key]['name'] = $value['name'];
					$this->result['data'][$key]['type'] = $value['type'];
					$this->result['data'][$key]['createTime'] = $value['createTime'];
					$this->result['data'][$key]['place_id'] = $value['place_id'];
					$this->result['data'][$key]['display'] = $value['display'];
					if ( $value['type'] == "blank") {
						$blank = TabBlank::model()->findAllByPk($value['id']);
						$this->result['data'][$key]['tabBlank'] = $blank[0]['content'];
					}
				}
			}
		} else {
			$this->result['errCode'] = 57;
			$this->result['errMsg'] = "getTabSite Undefined variable.";
		}
		echo CJSON::encode($this->result);
	}

	/*
	 * Get Social
	*/

	public function actiongetSocial() {
		if (isset($_GET['uid'])) {
			$uid = $_GET['uid'];
			$this->result['errCode'] = 0x0;
			$this->result['errMsg'] = "";
			$this->result['ref'] = "getSocial";
			$call = AccountDetail::model()->findAll(array( 'select'=> 'phone' ,"condition" => "uid = '" . $uid . "'"));
			if ( $call == null ) {
				$this->result['mobile'] = "no";
			} else {
				$this->result['mobile'] = $call[0]['phone'];
			}
			$facebook = Facebook::model()->findAll(array( 'select'=> 'fbid' ,"condition" => "uid = '" . $uid . "'"));
			if ( $facebook == null) {
				$this->result['facebook'] = "no";
			} else {
				$this->result['facebook'] = $facebook[0]['fbid'];
			}
			$twitter = Twitter::model()->findAll(array( 'select'=> 'twID' ,"condition" => "uid = '" . $uid . "'"));
			if ( $twitter == null ) {
				$this->result['twitter'] = "no";
			} else {
				$this->result['twitter'] = $twitter[0]['twID'];
			}
			$email = Account::model()->findAll(array( 'select'=> 'email' ,"condition" => "uid = '" . $uid . "'"));
			if ( $email == null ) {
				$this->result['email'] = "no";
			} else{
				$this->result['email'] = $email[0]['email'];
			}
		} else {
			$this->result['errCode'] = 59;
			$this->result['errMsg'] = "getSocial Undefined variable.";
		}
		echo CJSON::encode($this->result);
	}

	public function actionGetAccountInfo()
	{
		$resp = array();
		if(isset($_GET['id'])) {
			$id = $_GET['id'];
			$account = $this->getAccount($id);
			if($account == null) {
				$resp['errCode'] = 19;
				$resp['errMsg'] = 'Get User id Undefined variable.';
			}
			else {
				$resp['errCode'] = 0;
				$resp['data'] = $account;
			}
		}
		else {
			$resp['errCode'] = 19;
			$resp['errMsg'] = 'Get User id Undefined variable.';
		}
		echo CJSON::encode($resp);
	}

	public function actionSortTab()
	{
		$transaction = Yii::app()->db->beginTransaction();
		try {
			if(!isset($_GET['sort']) && !isset($_GET['uid'])) {
				throw new PlatwoException(60); //need variable sort
			}
			if (!Helper::checkUser($_GET['uid'])){
				throw new PlatwoException(32); //not found user
			}

			$sort = CJSON::decode($_GET['sort']);
			$uid = $_GET['uid'];

			$data = array();

			foreach($sort as $key => $value) {
				if($value == 1000000) continue; // tab reviews and detail id (for test)
				 
				$tab = Tab::model()->findByPk($value);
				$tab['seq'] = $key;
				 
				if (!Helper::checkSite($tab->place_id)){
					throw new PlatwoException(35); //not found site
				}
				 
				if (!Helper::checkOwnerSite($uid, $tab->place_id)){
					throw new PlatwoException(1000); //user not owner site
				}
				 
				if (!$tab->save()) {
					throw new PlatwoException(61); //update seq tab error
				}
			}

			$transaction->commit();
			echo CJSON::encode(array(
					'errorCode'=> 0
			));
		}
		catch (PlatwoException $e){
			$transaction->rollback();
			$e->saveLog();
			echo $e->toJSON();
		}
	}

	/*
	 * SITE_INDECENT = ไม่เหมาะสม/อนาจาร
	* SITE_FALSE = แอบอ้างหรือเป็นบัญชีปลอม
	* SITE_HARRY = ก่อกวน กลั่นแกล้ง
	* SITE_TEXT = อื่นๆ
	*/
	public function actionReport()
	{
		$transaction = Yii::app()->db->begintransaction();
		try {
			if(!isset($_GET['type'], $_GET['uid'], $_GET['data'])) {
				throw new PlatwoException(1100, 'Needs property type, uid, data');
			}
			if(!Helper::checkUser($_GET['uid'])){
				throw new PlatwoException(20);
			}
			$data = CJSON::decode($_GET['data']);
			$report = new Report();
			$report['type'] = $_GET['type'];
			$report['uid'] = $_GET['uid'];
			if(!$report->save()){
				throw new PlatwoException(2000);
			}
			if($_GET['type'] == 'SITE_INDECENT' OR $_GET['type'] == 'SITE_FALSE' OR $_GET['type'] == 'SITE_HARRY'){
				if(!isset($data['place_id'])){
					throw new PlatwoException(1100, 'Needs property data.place_id');
				}
				if(!Helper::checkSite($data['place_id'])){
					throw new PlatwoException(35);
				}
				$reportSite = new ReportSite;
				$reportSite->id = $report->id;
				$reportSite->place_id = $data['place_id'];
				if(!$reportSite->save()){
					throw new PlatwoException(2001);
				}
			}
			else if($_GET['type'] == 'SITE_TEXT'){
				if(!isset($data['place_id'], $data['text'])){
					throw new PlatwoException(1100, 'Needs property data.place_id, data.text');
				}
				if(!Helper::checkSite($data['place_id'])){
					throw new PlatwoException(35);
				}
				$reportSiteText = new ReportSiteText;
				$reportSiteText->id = $report->id;
				$reportSiteText->place_id = $data['place_id'];
				$reportSiteText->text = $data['text'];
				if(!$reportSiteText->save()){
					throw new PlatwoException(2002);
				}
			}
			else {
				throw new PlatwoException(2003);
			}
			$transaction->commit();
			$e = new PlatwoException(0);
			echo $e->toJSON();
		} catch(PlatwoException $e) {
			$transaction->rollback();
			$e->saveLog();
			echo $e->toJSON();
		}
	}
	
	public function actionUploadPlacePhoto()
	{
		$transaction = Yii::app()->db->begintransaction();
		try {
			if(!isset($_GET['place_id'], $_GET['uid'], $_GET['imgName'])){
				throw new PlatwoException(1100, 'Need variable place_id, uid, imgName');
			}
			$place_id = $_GET['place_id'];
			$uid = $_GET['uid'];
			$imgName = $_GET['imgName'];
			if(isset($_GET['albumId'])) {
				$album = Gallery::model()->findByPk($_GET['albumId']);
				if($album == null){
					throw new PlatwoException(9999, 'album not found');
				}
				$photo_group = $album->photo_group;
			}
			else {
				$site = Site::model()->findByPk($place_id);
				if($site == null){
					throw new PlatwoException(9999, 'site not found');
				}
				$photo_group = $site->photo_group;
			}
			$photoGroup = PhotoGroup::model()->findByPk($photo_group);
			if($photoGroup == null) {
				$photoGroup = new PhotoGroup();
				$photoGroup->photo_count = 0;
				if(!$photoGroup->save()) {
					throw new PlatwoException(1201, 'Save photo Group Error.');
				}
				$site->photo_group = $photoGroup->photo_group_id;
				if(!$site->save()) {
					throw new PlatwoException(1202, 'Update Place photo_group Error.');
				}
			}
			
			$data = array();
			$photo = new Photo();
			
			$data['photo_group'] = $photo->photo_group = $photoGroup->photo_group_id;
			$data['photo_url'] = $photo->photo_url = $_GET['imgName'];
			if(Photo::model()->count("photo_group=:photo_group", array(':photo_group'=> $photo_group)) != 0) {
				$criteria = new CDbCriteria();
				//$criteria->select = "seq";
				$criteria->condition = "photo_group=:photo_group";
				$criteria->order = "seq DESC";
				$criteria->params = array(':photo_group'=> $photo_group);
				$seq = 0;
				$buffer = Photo::model()->find($criteria);
				if($buffer != null) { $photo->seq = $buffer->seq + 1; }
			}
			if(!$photo->save()) {
				throw new PlatwoException(1201, 'Save Photo Error.');
			}
			$count = Photo::model()->count("photo_group=:photo_group", array(':photo_group'=> $photoGroup->photo_group_id));
			$data['photo_id'] = $data['id'] = $photo->photo_id;
			$data['seq'] = $photo->seq;
			$resp = array(
				'errorCode'=> 0,
				'errorMessage' => '',
				'data'=> $data,
			);
			$transaction->commit();
			echo CJSON::encode($resp);
		} catch(PlatwoException $e) {
			$transaction->rollback();
			echo $e->toJSON();
		}
	}
	
	public function actionGetPhotoByOwner()
	{
		if(isset($_GET['place_id'])) {
			$site = Site::model()->findByPk($_GET['place_id']);
			$photos = Photo::model()->findAllByAttributes(array('photo_group'=> $site->photo_group));
			$resp = array(
				'errorCode'=> 0,
				'errorMessage'=> '',
				'data'=> $photos,
			);
			echo CJSON::encode($resp);
		}
	}
	
	public function actionGetPhotoAtPlace()
	{
		if(isset($_GET['place_id'])) {
			$reviews = Review::model()->findAllByAttributes(array('place_id'=> $_GET['place_id']));
			$photos = array();
			foreach($reviews as $key => $value) {
				if($value->photo_group != null){
					$photos = array_merge($photos, Photo::model()->findAllByAttributes(array('photo_group'=> $value->photo_group)));
				}
			}
			$resp = array(
				'errorCode'=> 0,
				'errorMessage'=> '',
				'data'=> $photos,
			);
			echo CJSON::encode($resp);
		}
	}
	
	public function actionCreateAlbum()
	{
		$transaction = Yii::app()->db->begintransaction();
		try {
			if(isset($_GET['place_id'], $_GET['title'])) {
				$photoGroup = new PhotoGroup();
				if(!$photoGroup->save()) {
					throw new PlatwoException(9999, "Can't create photogroup record");
				}
				$lastAlbum = Gallery::model()->findByAttributes(array("place_id"=> $_GET['place_id']), array("order"=> "seq DESC"));
				if($lastAlbum == null) { $seq = 0; }
				else { $seq = $lastAlbum->seq + 1; }
				
				$album = new Gallery();
				$album->place_id = $_GET['place_id'];
				$album->title = $_GET['title'];
				$album->photo_group = $photoGroup->photo_group_id;
				$album->seq = $seq;
				if(!$album->save()){
					throw new PlatwoException(9999, "Can't create gallery record".CJSON::encode($album->getErrors()));
				}
				$transaction->commit();
				echo CJSON::encode($album->getAttributes());
			}
		} catch(PlatwoException $e) {
			$transaction->rollback();
			echo $e->toJSON();
		}
	}
	
	public function actionGetAlbums()
	{
		if(isset($_GET['place_id'])) {
			$albums = Gallery::model()->findAllByAttributes(array('place_id'=> $_GET['place_id']), array("order"=> "seq ASC"));
			$resp = array();
			foreach($albums as $key => $value) {
				$buffer = $value->getAttributes();
				$photoGroup = PhotoGroup::model()->findByPk($buffer['photo_group']);
				$photo = Photo::model()->findByAttributes(array('photo_group'=> $buffer['photo_group']), array("order"=> "seq DESC"));
				$buffer['photo_count'] = $photoGroup->photo_count;
				$buffer['cover_url'] = ($photo == null) ? 'images/album_blank.png': $photo->photo_url;
				$resp[] = $buffer;
			}
			echo CJSON::encode($resp);
		}
	}
	
	public function actionDelAlbum()
	{
		try {
			if(!isset($_GET['id'])) {
				throw new PlatwoException(1100, 'Needs property id');
			}
			$album = Gallery::model()->findByPk($_GET['id']);
			if($album != null) {
				$photoGroup = PhotoGroup::model()->findByPk($album->photo_group);
				if($photoGroup != null) {
					$photoGroup->delete();
				}
				$album->delete();
			}
			echo CJSON::encode(array('success'=> true));
		} catch(PlatwoException $e) {
			echo $e->toJSON();
		}
	}

	public function actionDelPhoto()
	{
		try {
			if(!isset($_GET['id'])) {
				throw new PlatwoException(1100, 'Needs property id');
			}
			$photo = Photo::model()->findByPk($_GET['id']);
			if($photo != null) { $photo->delete(); }
		} catch(PlatwoException $e) {
			echo $e->toJSON();
		}
	}
	
	public function actionRemovePhoto()
	{
		try {
			if(!isset($_GET['photo_id'])) {
				throw new PlatwoException(1100, 'Needs property photo_id');
			}
			$photo = Photo::model()->findByPk($_GET['photo_id']);
			if(!$photo->delete()){
				throw new PlatwoException(9999, 'Can not Delete Photo');
			}
		} catch(PlatwoException $e) {
			echo $e->toJSON();
		}
	}
	
	public function actionDoneUpload()
	{
		$transaction = Yii::app()->db->begintransaction();
		try {
			if(!isset($_GET['photos'])) { $_GET['photos'] = array(); }
			if(!isset($_GET['mode'], $_GET['place_id'], $_GET['photos'])) {
				throw new PlatwoException(1100, 'Needs property mode, place_id, photos');
			}
			if($_GET['mode'] == 'newAlbum') {
				if(!isset($_GET['albumName'], $_GET['albumId'])) {
					throw new PlatwoException(1100, 'Needs property albumName');
				}
				$album = Gallery::model()->findByPk($_GET['albumId']);
				if($album == null) {
					throw new PlatwoException(9999, 'not found album');
				}
				$album->title = $_GET['albumName'];
				if(!$album->save()) {
					throw new PlatwoException(9999, 'can not save album');
				}
				$photo_group = $album->photo_group;
			}
			else if($_GET['mode'] == 'all') {
				$site = Site::model()->findByPk($_GET['place_id']);
				if($site == null) {
					throw new PlatwoException(9999, 'not found site');
				}
				$photo_group = $site->photo_group;
			}
			else if($_GET['mode'] == 'inAlbum') {
				if(!isset($_GET['albumId'])) {
					throw new PlatwoException(1100, 'Needs property albumName');
				}
				$album = Gallery::model()->findByPk($_GET['albumId']);
				if($album == null) {
					throw new PlatwoException(9999, 'not found album');
				}
				$photo_group = $album->photo_group;
			}
			foreach($_GET['photos'] as $key => $value) {
				$photo = Photo::model()->findByPk($value['photo_id']);
				if($photo != null) {
					$photo->photo_group = $photo_group;
					if(isset($value['caption'])) {
						$photo->caption = $value['caption'];
					}
					if(!$photo->save()) {
						throw new PlatwoException(9999, 'can not save photo');
					}
				}
			}
			$transaction->commit();
		} catch(PlatwoException $e) {
			$transaction->rollback();
			echo $e->toJSON();
		}
		
	}
	
	public function actionGetPlacePhotos()
	{
		try {
			if(!isset($_GET['place_id'])){ throw new PlatwoException(9999, 'Need property place_id'); }
			$type = isset($_GET['type']) ? $_GET['type']: 'all';
			$groups = array();
			if($type == 'all') {
				/*
				$albums = array();
				$albums = Gallery::model()->findAllByAttributes(array('place_id'=> $_GET['place_id']));
				foreach($albums as $key => $album) {
					$groups[] = $album->photo_group;
				}
				*/
				$site = Site::model()->findByPk($_GET['place_id']);
				if($site == null){
					throw new PlatwoException(9999, 'Site not found');
				}
				$groups[] = $site->photo_group;
			}
			$criteria = new CDbCriteria();
			$criteria->addInCondition('photo_group', $groups);
			$criteria->order = "seq";
			$photos = Photo::model()->findAll($criteria);
			$photos = $this->eachGetAttributes($photos);
			echo CJSON::encode($photos);
		} catch(PlatwoException $e) {
			echo $e->toJSON();
		}
	}
	
	public function actionGetAlbumPhotos()
	{
		try {
			if(!isset($_GET['gallery_id'])){ throw new PlatwoException(9999, 'Need property gallery_id'); }
			$album = Gallery::model()->findByPk($_GET['gallery_id']);
			if($album == null){ throw new PlatwoException(9999, 'Album not found'); }
			$photos = Photo::model()->findAllByAttributes(array('photo_group'=> $album->photo_group), array("order"=> "seq"));
			$photos = $this->eachGetAttributes($photos);
			echo CJSON::encode($photos);
		} catch(PlatwoException $e) {
			echo $e->toJSON();
		}
	}
	
	// ***************************** internal function *************************************//
	
	public function getAccount($id)
	{
		$data = array();
		$account = Account::model()->with('place')->findByPk($id);
		if($account != null) {
			$data['id'] = $account->uid;
			$data['uid'] = $account->uid;
			$data['email'] = $account->email;
			$data['username'] = $account->username;
			$data['name'] = $account->name;
			$data['confirm_email'] = $account->confirm_email;
			$data['confirm_phone'] = $account->confirm_phone;

			if(isset($account->place)) {
				$data['site'] = $account->place->attributes;
			}
			return $data;
		}
		return null;
	}

	public function getRateAll($id)
	{
		$rateAll = array(
				'r1' => Review::model()->count("place_id=:place_id and rate='1'", array(':place_id'=> $id)),
				'r2' => Review::model()->count("place_id=:place_id and rate='2'", array(':place_id'=> $id)),
				'r3' => Review::model()->count("place_id=:place_id and rate='3'", array(':place_id'=> $id)),
				'r4' => Review::model()->count("place_id=:place_id and rate='4'", array(':place_id'=> $id)),
				'r5' => Review::model()->count("place_id=:place_id and rate='5'", array(':place_id'=> $id)),
		);
		$rateAll['max'] = max($rateAll);
		$rateAll['rateCount'] = $rateAll['r1'] + $rateAll['r2'] + $rateAll['r3'] + $rateAll['r4'] + $rateAll['r5'];
		return $rateAll;
	}
	
	public function eachGetAttributes($models, $attributes = true)
	{
		$data = array();
		foreach($models as $key => $model) {
			$data[] = $model->getAttributes($attributes);
		}
		return $data;
	}
}